// t3Pillar1.txt
// By Lazarus.
// Thanks a bunch to Niemand for all the help with the targeting algorithm.
// Looks for enemy with low health, and then shocks them. 
// Party members are more likely to be shocked. Does 10d20 damage
// When dies, swaps terrain at its own spot to broken pillar.
begincreaturescript;
variables;
short best,i,status,type,next,new,targ;
body;

beginstate init_state;
	set_mobility(ME,0);
	if(get_flag(250,7) > 0)
		erase_char(ME);
break;

beginstate dead_state;
run_town_script(13);
break;

beginstate start_state;
if(get_flag(3,15) == 1)
{	// Look for a target, attack it if visible
	next = 3;
	
	set_state_continue(4);
		
	// Have I been hit? Strike back!
	if (who_hit_me() >= 0) {
		set_target(ME,who_hit_me());
		set_state_continue(3);
	}

	// if we're in combat and the above didn't give me anything to do, just
	// stop now. Otherwise, game will keep running script, and that eats up CPU time.
	if (am_i_doing_action() == FALSE)
		end_combat_turn();
}
break;

beginstate 3; // attacking
	if ((target_ok() == FALSE) || (can_see_char(get_target()) == 0))
		set_state(START_STATE);
	if(new == 1){ //Mix things up and choose a new target
		next = 3;
		set_state_continue(4);
	}
	type = get_ran(1,1,6);
	while(type == 4){
		type = get_ran(1,1,6);
	}
	status = get_ran(1,101,110);
	if(status == 101)
		status = 0;
	if(status == 102)
		status = 6;
	if(status == 103)
		status = 7;
	if(status == 104)
		status = 8;
	if(status == 105)
		status = 10;
	if(status == 106)
		status = 11;
	if(status == 107)
		status = 12;
	if(status == 108)
		status = 18;
	if(status == 109)
		status = 20;
	if(status == 110)
		status = 21;
	if(can_see_char(get_target())){
		put_jagged_zap(my_loc_x(),my_loc_y(),char_loc_x(get_target()),char_loc_y(get_target()),1);
		put_boom_on_char(get_target(),6,0);
		run_animation();
		damage_char(get_target(),get_ran(10,1,20),type);
		set_char_status(get_target(),status,6,0,1);
		print_named_str(ME,"fires a bolt of energy.");
		new = 1;
		deduct_ap(3); 
	}
break;

beginstate 4; //Targetting state
	targ = -1;
	best = 30000;
	i = 0;
	while(i < 120){
		if((char_ok(i) == 1) && (char_attitude_to_char(ME,i) == 2) && (dist_to_char(i) < 12) && can_see_char(i) && (get_char_status(i,29) == 0)){
			status = get_health(i);
			if(i < 6) //a party member
				status = status/3;
			status = status + get_ran(1,0,100);
			if((status + dist_to_char(i)) < best){
				targ = i;
				best = (status + dist_to_char(i));
			}
		}
		i = i + 1;
	}
	set_target(ME,targ);
	if(targ == -1)
		set_state(START_STATE);
	new = 0;
	set_state_continue(next);
break;
